<template>
  <BasicModal @register="registerModal" title="选择目录" width="500" @ok="onSubmit" @cancel="onCancel">
    <a-spin :spinning="loading"> <a-directory-tree :treeData="treeData" :loadData="onLoadData" @select="onSelect" /> </a-spin>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { BasicModal, useModalInner } from '/@/components/Modal';

  export default defineComponent({
    name: 'FileSelectModal',
    components: { BasicModal },
    emits: ['select', 'register'],
    setup(_, { emit }) {
      const loading = ref(true);
      const treeData = ref([]);
      const selectedKey = ref('');
      const [registerModal, { closeModal }] = useModalInner(async () => {
        selectedKey.value = '';
        if (treeData.value.length === 0) {
          loadRoot();
        }
      });
      function onSubmit() {
        emit('select', selectedKey.value);
        closeModal();
      }
      function onCancel() {
        closeModal();
      }
      async function loadRoot() {
        loading.value = true;
        treeData.value = await defHttp.get({ url: '/api-online/online/cgform/head/rootFile' }).finally(() => {
          loading.value = false;
        });
      }
      async function onLoadData(treeNode) {
        if (treeNode.dataRef.children) {
          return;
        }
        let params = {
          parentPath: treeNode.dataRef.key,
        };
        treeNode.dataRef.children = await defHttp.get({ url: '/api-online/online/cgform/head/fileTree', params });
        treeData.value = [...treeData.value];
      }
      function onSelect(selectedKeys) {
        selectedKey.value = selectedKeys[0];
      }
      return { loading, treeData, onLoadData, onSelect, onSubmit, onCancel, registerModal };
    },
  });
</script>
<style scoped></style>
